const Question = require("../models/examination");

class Examinations {
  async find(ctx) {
    ctx.body = await Question.find();
  }

  // 按照题的类型分类查询
  async findByType(ctx) {
    const res = await Question.find({ type: ctx.params.type });
    if (!res) {
      ctx.throw(404, "查询结果为空！");
    }
    ctx.body = res;
  }

  // 搜索框使用
  async findByTitle(ctx) {
    console.log(ctx.query);
    const { keywords } = ctx.query;
    const res = await Question.find({
      title: { $regex: keywords, $options: "$i" }
    });
    if (!res) {
      ctx.throw(404, "查询结果为空！");
    }
    ctx.body = res;
  }

  // 结果分页
  async slicePages(ctx) {
    const { currentPage, steps, type } = ctx.query;
    if (isNaN(steps * currentPage)) {
      ctx.throw(403, "输入参数格式有误！");
    }
    // 例子：question/slice?currentPage=1&steps=5&type=radio
    // res={currentPages:1, steps:5, questions:[a,b,c], }
    // 获取总长度，获取分页数，
    const cpage = currentPage * 1 || 0;
    const csteps = steps * 1 || 5;
    const count = await Question.countDocuments();
    const pages = parseInt(count / csteps) + 1;
    let questionSlice = undefined;
    if (type) {
      questionSlice = await Question.find({ type })
        .skip(cpage * csteps)
        .limit(csteps);
      // .sort({ _id: 1 });
    } else {
      questionSlice = await Question.find({})
        .skip(cpage * csteps)
        .limit(csteps);
      // .sort({ _id: 1 });
    }

    ctx.body = { pages, questionSlice, currentPage: cpage, steps: csteps };
  }
  // 创建问题
  async create(ctx) {
    const { title } = ctx.request.body;
    const res = await Question.findOne({ title });
    if (res) {
      ctx.throw(409, "问题已经存在");
    }
    const success = await new Question(ctx.request.body).save();
    ctx.body = success;
  }

  async update(ctx) {
    const res = await Question.findOneAndUpdate(
      { id: ctx.params.id },
      ctx.request.body,
      { new: true }
    );
    if (!res) {
      ctx.throw(404, "要更新的问题不存在！");
    }
    ctx.body = res;
  }

  async del(ctx) {
    const res = await Question.findOneAndRemove({ id: ctx.params.id });
    if (!res) {
      ctx.throw(404, "要删除的问题不存在");
    }

    ctx.status = 204;
  }
}
module.exports = new Examinations();
